import sensor, image, time,lcd
import pyb
from time import sleep
from os import listdir
from math import floor,ceil
from gc import collect
from button import BUTTON
from findpyfile import FINDPYFILE
global click_timer
global icon_W,icon_H
global py_file_quantity,py_file_names
global img_homepage,icon_mask,number,size
global select,last_select
icon_W=52
icon_H=65
icon_S=icon_W-5
icon_N=4
lcd.init(type=2,width=240,height=320)
lcd.set_direction(2)
lcd.clear()
button=BUTTON()
pyfile=FINDPYFILE()
py_file_quantity=pyfile.py_file_quantity
py_file_names=pyfile.py_file_names
icon_mask=sensor.alloc_extra_fb(icon_W,icon_H,sensor.RGB565)
img_homepage = sensor.alloc_extra_fb(lcd.width(),lcd.height(),sensor.RGB565)
def cut_round_corners(img,r=10):
    img.draw_circle(r,r,r,fill=True)
    img.draw_circle(icon_W-r,r,r,fill=True)
    img.draw_circle(r,icon_W-r,r,fill=True)
    img.draw_circle(icon_W-r,icon_W-r,r,fill=True)
    img.draw_rectangle(r,0,icon_W-r*2,icon_W,fill=True)
    img.draw_rectangle(0,r,icon_W,icon_W-r*2,fill=True)
    img.draw_rectangle(0,icon_W,icon_W,icon_H-icon_W,fill=True)
def draw_icon(m,s,erase=True):
    global img_homepage,r,number,size,n
    number=m
    size=s
    if size>icon_W:size=icon_W
    elif size<10:size=10
    try:
        if erase:
            img_homepage.draw_rectangle((number%icon_N)*(icon_H-5),floor(number/icon_N)*icon_H,icon_W,icon_H,color=(0,0,0),fill=True)
        exec('img_homepage.draw_image(icon'+str(number)+',(number%icon_N)*(icon_H-5)+round((icon_W-size)/2),floor(number/icon_N)*icon_H+round((icon_W-size)/2),x_size=size,y_size=size+icon_H-icon_W)')
    except:
        pass
for n in range(py_file_quantity):
    exec('icon'+str(n)+'=sensor.alloc_extra_fb(icon_W,icon_H,sensor.RGB565)')
    try:
        exec("icon"+str(n)+".draw_image(image.Image('/ICONS/"+py_file_names[n]+".bmp',copy_to_fb=True), 0,0,x_size=icon_W,y_size=icon_W)")
    except:
        try:
            exec("icon"+str(n)+".draw_image(image.Image('/ICONS/unknow_program.bmp',copy_to_fb=True), 0,0,x_size=icon_W,y_size=icon_W)")
        except:
            exec('icon'+str(n)+'.draw_rectangle(0,0,icon_W,icon_W,fill=True)')
    cut_round_corners(icon_mask,1)
    exec('icon'+str(n)+'.b_and(icon_mask)')
    if len(py_file_names[n])<10:
        exec('icon'+str(n)+'.draw_string(round((10-len(py_file_names[n]))*2),icon_W+2,py_file_names[n],scale=1.0,x_spacing=1,mono_space=False)')
    elif len(py_file_names[n])>=10:
        exec('icon'+str(n)+'.draw_string(0,icon_W+2,py_file_names[n][:9]+"..",scale=1.0,x_spacing=1,mono_space=False)')
for number in range(py_file_quantity):
    draw_icon(number,icon_S)
draw_icon(1,icon_W)
lcd.display(img_homepage)
def pyselect():
    global last_select,select
    button.key_event=0
    click_timer=time.ticks()
    while True:
        button.event()
        if button.state():
            while button.state():  pass
            if time.ticks()-click_timer>2000:
                break
            if time.ticks()-click_timer<300:
                select=select+1
                if select >= py_file_quantity:  select=0
                if select!=last_select:
                    draw_icon(select,icon_W)
                    draw_icon(last_select,icon_S)
                    last_select=select
                    lcd.display(img_homepage)
        else:
            click_timer=time.ticks()
    while button.state():  pass
    try:
        print('exec start:/'+str(py_file_names[select]))
        collect()
        exec_file=open('/%s.py'%str(py_file_names[select])).read()
        exec(exec_file)
        del exec_file
        print('exec end:/'+str(py_file_names[select]))
    except Exception as err:
        img_homepage.draw_string(0,280,'ERR:'+str(err),scale=1.0,x_spacing=1,mono_space=False,color=(139,0,255))
        lcd.display(img_homepage)
        print('ERR:'+str(err))
        while not button.state():  pass
        img_homepage.draw_rectangle(0,280,240,40,color=(0,0,0),fill=True)
    while button.state():  pass
    for number in range(py_file_quantity):
        draw_icon(number,icon_S)
    draw_icon(select,icon_W)
    lcd.display(img_homepage)
select=1
last_select=1
click_timer=time.ticks()
while True:
    if button.state():
        pyselect()
    else:
        click_timer=time.ticks()
